﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Linq.Dynamic;
using System.Web.Mvc;
using SDT.Model;
using SDT.Lib.Common;
using SDT.Admin.Properties;
using SDT.Admin.ViewModels;
using SDT.Lib.Paging;
using System.Web.UI.WebControls;
using System.IO;
using System.Data.Linq;
using SDT.Lib.Helpers;
using System.Threading;
using System.Globalization;

namespace SDT.Admin.Controllers
{
    /// <summary>
    /// Author: Takamaru Nguyen
    /// Date: 09/07/2011
    /// </summary>
    [RoleHelper(Roles = RoleSystem.Polls)]
    public class PollsController : Controller
    {
        ChoVietDataContext eDataContext = new ChoVietDataContext();
        public PollsController()
        {
            var currentCulture = Thread.CurrentThread.CurrentCulture;
            Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture("fr-FR");
        }
        
        //
        // GET: /Polls/

        public ActionResult Index(int? page)
        {
            try
            {
                if (UserManager.CheckRole(RoleSystem.Polls))
                {
                    if (page == null)
                        page = 1;
                    string order = UserState.getUserStateFromRequest("polls.order", "order", "ID").ToString();
                    string orderDir = UserState.getUserStateFromRequest("polls.orderDir", "orderDir", "desc").ToString();
                    int catID = Convert.ToInt32(UserState.getUserStateFromRequest("polls.CurrentCat", "CurrentCat", 0));
                    string strPub = UserState.getUserStateFromRequest("polls.CurrentPubStatus", "CurrentPubStatus", "").ToString();
                    string keyword = UserState.getUserStateFromRequest("polls.Keyword", "Keyword", "").ToString();
                    int pageSize = int.Parse(UserState.getUserStateFromRequest("polls.pageSize", "PageSize", 20).ToString());

                    int? currentPub = null;
                    if (!string.IsNullOrEmpty(strPub))
                        currentPub = Convert.ToInt32(strPub);

                    var pros = eDataContext.Polls
                        .Where(p => currentPub.HasValue ? p.PubYN == (currentPub.HasValue && currentPub.Value == 1 ? true : false) : true)
                        .Where(p => (string.IsNullOrEmpty(keyword) ? true : p.PollContent.ToLower().Contains(keyword.ToLower().Trim())))
                        .OrderBy(string.Format("{0} {1}", order, orderDir))
                        .ToPagedList(page.Value - 1, pageSize);

                    ViewData["orderDir"] = orderDir;
                    ViewData["order"] = order;

                    return View(new PollViewModels
                    {
                        Polls = pros,
                        CurrentPubStatus = currentPub,
                        Keyword = keyword
                    });
                }
                else
                {
                    ViewData[Messages.MessageInfo] = Messages.NOT_PERMIT;
                    return View();
                }
            }
            catch (Exception exp)
            {
                ViewData[Messages.MessageInfo] = exp.Message;
                return View();
            }
        }

        //
        // GET: /Polls/Details/5

        public ActionResult Details(int id)
        {
            try
            {
                if (UserManager.CheckRole(RoleSystem.Polls))
                {
                    Poll po = eDataContext.Polls.Where(p => p.ID == id).FirstOrDefault();
                    List<SDT.Model.Menu> listM = (from pol in eDataContext.Polls
                                                  join pm in eDataContext.PollMenuMaps on pol.ID equals pm.PollID into pmm
                                                  from docu in pmm.DefaultIfEmpty()
                                                  join m in eDataContext.Menus on docu.MenuID equals m.ID
                                                  where pol.ID == id
                                                  select m).ToList();
                    List<PollCase> pCase = eDataContext.PollCases.Where(pc => pc.PollID == id).ToList();
                    return View(new PollInputModels
                    {
                        Poll = po,
                        ListMenus = listM,
                        PollCases = pCase,
                        ID = id
                    });
                }
                else
                {
                    ViewData[Messages.MessageInfo] = Messages.NOT_PERMIT;
                    return View(new PollInputModels
                    {
                        ID = id
                    });
                }
            }
            catch (Exception exp)
            {
                ViewData[Messages.MessageInfo] = exp.Message;
                return View(new PollInputModels
                {
                    ID = id
                });
            }
        }

        //
        // GET: /Polls/Create

        public ActionResult Create()
        {
            try
            {
                if (UserManager.CheckRole(RoleSystem.Polls))
                {
                    List<SDT.Model.Menu> menu = eDataContext.Menus.Where(m => m.PubYN == true).ToList();

                    return View(new PollInputModels
                    {
                        ListMenus = menu
                    });
                }
                else
                {
                    ViewData[Messages.MessageInfo] = Messages.NOT_PERMIT;
                    return View();
                }
            }
            catch (Exception exp)
            {
                ViewData[Messages.MessageInfo] = exp.Message;
                return View();
            }
        } 

        //
        // POST: /Polls/Create

        [HttpPost]
        [ValidateInput(false)]
        public ActionResult Create(PollInputModels m)
        {
            try
            {
                if (UserManager.CheckRole(RoleSystem.Polls))
                {
                    UpdateModel(m);
                    m.Poll.AddBy = UserManager.GetUserId();
                    m.Poll.AddDate = DateTime.Now;
                    
                    eDataContext.Polls.InsertOnSubmit(m.Poll);
                    eDataContext.SubmitChanges();

                    // Map with menu
                    foreach(int mID in m.MenuID)
                    {
                        PollMenuMap pM = new PollMenuMap();
                        pM.MenuID = mID;
                        pM.PollID = m.Poll.ID;
                        eDataContext.PollMenuMaps.InsertOnSubmit(pM);
                        eDataContext.SubmitChanges();
                    }
                    
                    // map with poll case
                    for (int i = 1; i <= m.PollCaseIndex; i++)
                    {
                        if (string.IsNullOrEmpty(Request["PollCase" + i]))
                            continue;
                        PollCase pC = new PollCase();
                        pC.nVotes = 0;
                        pC.PollID = m.Poll.ID;
                        pC.PollCase1 = Request["PollCase" + i];
                        eDataContext.PollCases.InsertOnSubmit(pC);
                        eDataContext.SubmitChanges();
                    }

                    return RedirectToAction("Index");
                }
                else
                {
                    ViewData[Messages.MessageInfo] = Messages.NOT_PERMIT;
                    return View();
                }
            }
            catch (Exception exp)
            {
                ViewData[Messages.MessageInfo] = exp.Message;
                return View();
            }
        }

        //
        // GET: /Polls/Edit/5
 
        public ActionResult Edit(int id)
        {
            try
            {
                if (UserManager.CheckRole(RoleSystem.Polls))
                {
                    List<SDT.Model.Menu> menus = eDataContext.Menus.Where(m => m.PubYN == true).ToList();
                    Poll po = eDataContext.Polls.Where(p => p.ID == id).FirstOrDefault();
                    List<int> listM = (from pol in eDataContext.Polls
                                                  join pm in eDataContext.PollMenuMaps on pol.ID equals pm.PollID into pmm
                                                  from docu in pmm.DefaultIfEmpty()
                                                  join m in eDataContext.Menus on docu.MenuID equals m.ID
                                                  where pol.ID == id
                                                  select m.ID).ToList();
                    List<PollCase> pCase = eDataContext.PollCases.Where(pc => pc.PollID == id).ToList();
                    return View(new PollInputModels
                    {
                        Poll = po,
                        ListMenus = menus,
                        MenuID = listM,
                        PollCases = pCase,
                        ID = id
                    });
                }
                else
                {
                    ViewData[Messages.MessageInfo] = Messages.NOT_PERMIT;
                    return View();
                }
            }
            catch (Exception exp)
            {
                ViewData[Messages.MessageInfo] = exp.Message;
                return View();
            }
        }

        //
        // POST: /Polls/Edit/5

        [HttpPost]
        [ValidateInput(false)]
        public ActionResult Edit(int id, PollInputModels m)
        {
            try
            {
                if (UserManager.CheckRole(RoleSystem.Polls))
                {
                    m.Poll = eDataContext.Polls.Where(p => p.ID == id).FirstOrDefault();
                    UpdateModel(m);
                    m.Poll.ModifyBy = UserManager.GetUserId();
                    m.Poll.ModifyDate = DateTime.Now;

                    eDataContext.SubmitChanges();

                    // Map with menu
                    List<PollMenuMap> pmMap = eDataContext.PollMenuMaps.Where(pm => pm.PollID == id).ToList();
                    if (pmMap != null && pmMap.Count() > 0)
                    {
                        eDataContext.PollMenuMaps.DeleteAllOnSubmit(pmMap);
                        eDataContext.SubmitChanges();
                    }
                    foreach (int mID in m.MenuID)
                    {
                        PollMenuMap pM = new PollMenuMap();
                        pM.MenuID = mID;
                        pM.PollID = m.Poll.ID;
                        eDataContext.PollMenuMaps.InsertOnSubmit(pM);
                        eDataContext.SubmitChanges();
                    }

                    // map with poll case
                    List<PollCase> pCase = eDataContext.PollCases.Where(pc => pc.PollID == id).ToList();
                    if (pCase != null && pCase.Count() > 0)
                    {
                        eDataContext.PollCases.DeleteAllOnSubmit(pCase);
                        eDataContext.SubmitChanges();
                    }
                    for (int i = 1; i <= m.PollCaseIndex; i++)
                    {
                        if (string.IsNullOrEmpty(Request["PollCase" + i]))
                            continue;
                        PollCase pC = new PollCase();
                        pC.nVotes = 0;
                        pC.PollID = m.Poll.ID;
                        pC.PollCase1 = Request["PollCase" + i];
                        eDataContext.PollCases.InsertOnSubmit(pC);
                        eDataContext.SubmitChanges();
                    }

                    return RedirectToAction("Index");
                }
                else
                {
                    ViewData[Messages.MessageInfo] = Messages.NOT_PERMIT;
                    return View();
                }
            }
            catch (Exception exp)
            {
                ViewData[Messages.MessageInfo] = exp.Message;
                return View();
            }
        }

        //
        // GET: /Polls/Delete/5

        public ActionResult Delete(int id)
        {
            try
            {
                if (UserManager.CheckRole(RoleSystem.Polls))
                {
                    Poll p = eDataContext.Polls.Where(po => po.ID == id).FirstOrDefault();
                    
                    return View(p);
                }
                else
                {
                    ViewData[Messages.MessageInfo] = Messages.NOT_PERMIT;
                    return View();
                }
            }
            catch (Exception exp)
            {
                ViewData[Messages.MessageInfo] = exp.Message;
                return View();
            }
        }

        //
        // POST: /Polls/Delete/5

        [HttpPost]
        public ActionResult Delete(int id, FormCollection collection)
        {
            try
            {
                if (UserManager.CheckRole(RoleSystem.Polls))
                {
                    Poll p = eDataContext.Polls.Where(po => po.ID == id).FirstOrDefault();
                    // delete map with menu
                    List<PollMenuMap> pmMap = eDataContext.PollMenuMaps.Where(pm => pm.PollID == id).ToList();
                    if (pmMap != null && pmMap.Count() > 0)
                    {
                        eDataContext.PollMenuMaps.DeleteAllOnSubmit(pmMap);
                        eDataContext.SubmitChanges();
                    }
                    // delete pollcase
                    List<PollCase> pCase = eDataContext.PollCases.Where(pc => pc.PollID == id).ToList();
                    if (pCase != null && pCase.Count() > 0)
                    {
                        eDataContext.PollCases.DeleteAllOnSubmit(pCase);
                        eDataContext.SubmitChanges();
                    }
                    // delete poll
                    eDataContext.Polls.DeleteOnSubmit(p);
                    eDataContext.SubmitChanges();

                    return RedirectToAction("Index");
                }
                else
                {
                    ViewData[Messages.MessageInfo] = Messages.NOT_PERMIT;
                    return View();
                }
            }
            catch (Exception exp)
            {
                ViewData[Messages.MessageInfo] = exp.Message;
                return View();
            }
        }
    }
}
